const Ws = require("ws");
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");

app.use("/uploads", express.static(__dirname + "/uploads"));
app.use(bodyParser());
app.use(cors());

require("./routes/upload.js")(app);

app.listen(7001, () => {
  console.log("http://localhost:7001");
});

const server = new Ws.Server({
  port: 8000,
});

const init = () => {
  bindEvent();
};

function bindEvent() {
  server.on("open", handleOpen);
  server.on("close", handleClose);
  server.on("error", handleError);
  server.on("connection", handleConnection);
}

function handleOpen(e) {
  console.log("open");
}
function handleClose(e) {
  console.log("close");
}
function handleError(e) {
  console.log("error");
}
function handleConnection(ws) {
  console.log("connection");
  ws.on("message", handleMsg);
}

function handleMsg(msg) {
  server.clients.forEach(c => {
    c.send(msg)
  });
}

init();
